import request from '@/axios'
import { check } from './baseModel'
import router from '@/router'

export interface loginForm {
    name: string
    password: string
}

export const loginRules = {
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在 3 到 20 个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 32, max: 32, message: '密钥长度是 32 位', trigger: 'blur' }
    ]
}

export interface Admin {
    token: string | null
    name: string | null
}

const key = "admin"

export class AdminUtils {

    static getAdmin(): Admin {
        return JSON.parse(localStorage.getItem(key) || '{"token": null, "name": null}')
    }

    static login(form: loginForm) {
        AdminApi.login(form)
        .then(data => {
            localStorage.setItem(key, JSON.stringify(data))
            router.push("/")
        })
    }

    static logout() {
        localStorage.setItem(key, '{"token": null, "name": null}')
        router.push("/login")
    }

}

class AdminApi {

    static baseUrl = "/admin"

    static async login(form: loginForm) {
        try {
            const response = await request.post(this.baseUrl + "/login", form)
            return check(response)
        }
        catch (error) { throw error }
    }

}